from typing import TypeVar, Generic, Optional

from pydantic import BaseModel

T = TypeVar('T')  # 泛型类型变量

SUCCESS_CODE: int = 1
ERROR_CODE: int = 0


class Response(BaseModel, Generic[T]):
    code: int
    message: Optional[str] = None
    data: Optional[T] = None

    @property
    def is_success(self) -> bool:
        """是否是成功响应"""
        return self.code == SUCCESS_CODE

    @classmethod
    def ok(cls) -> 'Response[T]':
        """创建成功响应"""
        return cls(code=SUCCESS_CODE)

    @classmethod
    def error(cls, message: str) -> 'Response[T]':
        """创建错误响应"""
        return cls(code=ERROR_CODE, message=message)

    @classmethod
    def customize(cls, code: int, message: str) -> 'Response[T]':
        """创建自定义响应"""
        return cls(code=code, message=message)

    def wrap(self, data: T) -> 'Response[T]':
        """封装数据并返回新的响应实例"""
        # 创建新实例以保持不可变性
        self.data = data
        return self

